import router from './router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router/index'
// 导入封装的标题
import getPageTitle from '@/utils/get-page-title'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 设置标题
  document.title = getPageTitle(to.meta.title)
  NProgress.start() // 开始进度条
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done() // 关闭进度条
    } else {
      document.title = getPageTitle(to.meta.title)
      if (!store.state.user.userInfo.userId) {
        // 调用action中的函数,获取用户信息返回的权限名
        const res = await store.dispatch('user/setuserInfo')
        console.log(res, 'resresres')
        // console.log(asyncRoutes, 'asyncRoutes')
        // 根据权限信息过滤得到用户可以访问的路由表
        const filtersRouter = asyncRoutes.filter(item => {
          return res.includes(item.children[0].name)
        })
        console.log(filtersRouter, 'filtersRouter')
        filtersRouter.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filtersRouter)
        store.commit('menu/setMemusList', filtersRouter)
        // bai'pi
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done() // 关闭进度条
    }
  }
})
// 页面跳转完成会经过这里
router.afterEach(() => {
  NProgress.done()
})
